// 参考： https://threejsfundamentals.org/threejs/lessons/threejs-post-processing.html
import { 
  BoxGeometry,
  Mesh,
  MeshBasicMaterial,
  PerspectiveCamera,
  Scene, 
  WebGLRenderer,
  Group,
} from "three";
import stats from '../utils/stats';
// 调用
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass";
import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer";
import { SSAOPass } from 'three/examples/jsm/postprocessing/SSAOPass';
import { GUI } from "dat.gui";

let renderer = setRenderer();
let camera = setCamera();
let scene = new Scene();

let amount = 50;
let xRange = 20;
let yRange = 20;
let zRange = 20;

let total = new Group();
for (let i = 0; i < amount; i++) {
  let boxGeom = new BoxGeometry(5, 5, 5);
  let boxMate = new MeshBasicMaterial({color: Math.random() * 0xffffff});
  let boxMesh = new Mesh(boxGeom, boxMate);

  let rX = Math.random() * xRange - xRange / 2;
  let rY = Math.random() * yRange - yRange / 2;
  let rZ = Math.random() * zRange - zRange / 2;

  let totalRotation = 2 * Math.PI;

  boxMesh.position.set(rX, rY, rZ);
  boxMesh.rotation.set(
    Math.random() * totalRotation,
    Math.random() * totalRotation,
    Math.random() * totalRotation
  );
  total.add(boxMesh);
}

scene.add(total);

let renderPass = new RenderPass(scene, camera);
let aoPass = new SSAOPass(scene, camera);
let composer = new EffectComposer(renderer);
composer.addPass(renderPass);
composer.addPass(aoPass);

const trackballControls = new OrbitControls(camera, renderer.domElement);

let gui = new GUI();
let controls = {
  radius: 1,
  aoClamp: 1,
  lumInfluence: 0,
  enabled: true
};
gui.add(controls, 'radius', 1, 10, 0.1).onChange(val => {
  aoPass.kernelRadius = val;
})
gui.add(controls, 'enabled').onChange(val => {
  aoPass.enabled = val;
})

render();
function render() {
  stats.update();
  trackballControls.update();

  total.rotation.x += 0.0001;
  total.rotation.y += 0.001;

  requestAnimationFrame(render);
  composer.render();
}


function setRenderer() {
  const renderer = new WebGLRenderer({ antialias: true });
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  // 支持阴影生成 
  renderer.shadowMap.enabled = true;
  document.body.appendChild(renderer.domElement);

  return renderer
}

function setCamera(): PerspectiveCamera {
  let camera = new PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000);
  camera.position.set(0, 20, 40);

  return camera;
}




